package cn.com.sp.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.com.sp.demo.service.IFileService;

@Controller
@RequestMapping(value = "file")
@EnableAutoConfiguration
public class FileController {

	@Autowired
	private IFileService fileService;

	private final static String path = "E:/fndwork/spring-boot-demo/src/main/resources/file/";
	// private final static String path = "f:/test/";

	@ResponseBody
	@RequestMapping("uploadFile2")
	public String uploadFile2(@RequestParam("file") MultipartFile file) throws IOException {
		String fileName = new Date().getTime() + file.getOriginalFilename();
		File newFile = new File(path + fileName);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		return fileName;
	}

	@ResponseBody
	@RequestMapping(value = "uploadFile")
	public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
		String fileName = new Date().getTime() + file.getOriginalFilename();
		try {
			// 获取输出流
			OutputStream os = new FileOutputStream(path + fileName);
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			InputStream is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
			os.close();
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return fileName;
	}

	@ResponseBody
	@RequestMapping("getFile")
	public void getFile(String fileName, HttpServletResponse response) throws IOException {
		// String paths = ResourceUtils.getURL("classpath:").getPath();
		File imageFile = new File(path + fileName);
		if (!imageFile.exists()) {
			return;
		}
		// 下载的文件携带这个名称
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		// 文件下载类型--二进制文件
		response.setContentType("application/octet-stream");
		try {
			FileInputStream fis = new FileInputStream(imageFile);
			byte[] content = new byte[fis.available()];
			fis.read(content);
			fis.close();
			ServletOutputStream sos = response.getOutputStream();
			sos.write(content);
			sos.flush();
			sos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
